
package com.project.base.common;

import net.sf.json.JSONObject;
import org.apache.http.client.ClientProtocolException;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class WeixinUtil {

    private static Logger log = Logger.getLogger(WeixinUtil.class);

    public static final String atUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s";// 获取access_token
    public static final String sendUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s"; // 发送微信消息url
    // #微信公众号上应用的CropID和Secret
    // public static final String CropID="wx7936a724bbb377ef";
    // public static final String
    // Secret="XUaUqBC3bRKdv0O7vHmN86qSrcP2g51fMEM6Zn7TPMyIualIZTDQwXBMmcEhCa8-" ;;
    // public static final Integer appID=2 ; //企业号中的应用id 2
    // public static final Integer userID=1 ; //部门成员id，zabbix中定义的微信接收者 2
    // public static final Integer partyID=1 ; //部门id，定义了范围，组内成员都可接收到消息 4

    /**
     * @return String
     * @Title: getAccessToken
     * @Description: 获取access_token
     */
    public static String getAccessToken(String cropID, String secret) {
        String url = String.format(atUrl, cropID, secret);
        String json = HttpsUtil.proxyRequestGet(url, null);
        JSONObject jsonObject = JSONObject.fromObject(json);
        String accessToken = (String) jsonObject.get("access_token");
        return accessToken;
    }

    /**
     * @param content
     * @return void
     * @Title: setInfo
     * @Description: 生成通过post请求发送消息的url 发送信息到微信 \n 换行 append("\n")
     */
    public static void setInfo(String content, String cropID, String secret,
                               String appID, String userID, String partyID) {
        String url = getSendUrl(cropID, secret);
        int num = 1000;// 消息内容，最长不超过2048个字节
        for (int i = 0; i <= content.length() / num; i++) {
            int num1 = num * (i + 1);// 结尾
            if (i == content.length() / num) {
                num1 = content.length();
            }
            // 生成post请求信息
            Map<String, Object> sParaTemp = getTextContent(appID, userID, partyID,
                    content.substring(num * i, num1));
            // 需要转换成json然后在作post请求
            // 发送post请求
            HttpsUtil.HttpResponseWrapper json;
            try {
                String data = JSONUtil.getJsonString4JavaPOJO(sParaTemp);
                json = HttpsUtil.requestPostData(url, data, "application/json",
                        HttpsUtil.CHARACTER_ENCODING);
                String result = json.getResponseString(HttpsUtil.CHARACTER_ENCODING);
                log.info("......WeixinUtil..content=" + content.substring(num * i, num1)
                        + ";result=" + result + ".......");
            } catch (ClientProtocolException e) {
                log.error("发送微信消息异常：", e);
            } catch (IOException e) {
                log.error("发送微信消息异常：", e);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @return String
     * @Title: getSendUrl
     * @Description: 微信发送信息地址
     */
    public static String getSendUrl(String cropID, String secret) {
        String url = String.format(sendUrl, getAccessToken(cropID, secret));
        return url;
    }

    /**
     * @param appID
     * @param userID
     * @param partyID
     * @param content
     * @return Map<String,Object>
     * @Title: getTextContent
     * @Description: 生成text信息格式
     */
    public static Map<String, Object> getTextContent(String appID, String userID,
                                                     String partyID, String content) {
        Map<String, Object> sParaTemp = new HashMap<String, Object>();
        Map<String, String> params = new HashMap<String, String>();
        params.put("content", content);
        sParaTemp.put("touser", userID.toString());
        sParaTemp.put("toparty", partyID.toString());
        sParaTemp.put("msgtype", "text");
        sParaTemp.put("agentid", appID.toString());
        sParaTemp.put("text", params);
        sParaTemp.put("safe", "0");
        return sParaTemp;
    }

    /**
     * @param title   语言/项目/标题
     * @param content 描述
     * @param range   影响范围
     * @param warn    警告信息
     * @param map     其他信息
     * @return void
     * @Title: setInfo
     * @Description: 发送信息到微信 已自动换行 发送信息到微信 \n 换行 append("\n")
     */
    public static void setInfo(String title, String content, String range, String warn,
                               Map<String, Object> map) {
        StringBuilder text = new StringBuilder("标题：").append(title).append("\n");
        text = text.append("描述：").append(content).append("\n");
        text = text.append("范围：").append(range).append("\n");
        text = text.append("警告：").append(warn).append("\n");
        if (null != map)
            for (Entry<String, Object> entry : map.entrySet()) {
                // Map.entry<Integer,String> 映射项（键-值对） 有几个方法：用上面的名字entry
                // entry.getKey() ;entry.getValue(); entry.setValue();
                // map.entrySet() 返回此映射中包含的映射关系的 Set视图。
                text = text.append(entry.getKey()).append("：").append(entry.getValue())
                        .append("\n");
            }
//		WeixinUtil.setInfo(text.toString());
    }

    public static void sendWchat(String configName, String content) {

        ConfigManager config = ConfigManager.getInstance();
        String cropID = config.getParamValue(configName, "CropID", "wx74bd6593bd7df6b7");
        String secret = config.getParamValue(configName, "Secret", "LRxo0N6_1iN6IF6eKJ5md7yw-Al_Wq8an-3aBJ7EfzXoM5iUCGhqnwRwryGNef80");
        String appID = config.getParamValue(configName, "AppID", "3");
        String userID = config.getParamValue(configName, "UserID", "2");
        String partyID = config.getParamValue(configName, "PartyID", "4");
        setInfo(content, cropID, secret, appID, userID, partyID);

    }

    public static void main(String[] args) {
//		String cropID = "wx74bd6593bd7df6b7";
//		String secret = "LRxo0N6_1iN6IF6eKJ5md7yw-Al_Wq8an-3aBJ7EfzXoM5iUCGhqnwRwryGNef80";
//		String appID = "3";
//		String userID = "2";
//		String partyID = "4";
//		String  content = "标题：慧眼系统消息告警 \n" +"内容：数据抓取环节出现异常，异常数据量超过预警阈值：10，请您尽快核查原因，谢谢！";
//		setInfo(content, cropID, secret, appID, userID, partyID);
    }
}
